<template>
	<view>
		<view class="content">
			<view class="locate-item" @click="open">
				<view class="locate-images">
					<image style="width: 100%; height: 100%;" mode="aspectFit" :src="icons.locate"></image>
				</view>
				<template v-if="currentEqiupment.eqiupment_id">
					<view class="locate-title">
						{{ currentEqiupment.eqiupment_name }}
					</view>
					<view>
						<view class="triangle_border_right">
							<span></span>
						</view>
					</view>
				</template>
			</view>
			<view style="height: 240rpx;margin-bottom: 20rpx;">
				<swiper class="swiper-box" @change="change" style="height: 200rpx;">
					<swiper-item v-for="(item ,index) in info" :key="index">
						<image style="width: 100%; height: 100%;" :src="item.content"></image>
					</swiper-item>
				</swiper>
				<view class="dot-content">
					<view v-for="(item ,index) in info" :key="index" class="swiper-dot" :class="current_index === index? 'active':''">
					</view>
				</view>
			</view>
			<view class="goods-list" v-for="(items, index) in list" :key="index">
				<view class="goods-title">
					<view class="goods-icon">
						<image style="width: 100%; height: 100%;" mode="aspectFit" :src="items.goods_date === date?icons.today:icons.tomorrow"></image>
					</view>
					<view class="items-title">{{ dateMode(new Date(items.goods_date), 'week') }}</view>
					<view class="goods-note"></view>
				</view>
				<view class="goods-content" @click="showDtail(items.id, items.goods_date)">
					<view class="goods-img">
						<image style="width: 240rpx; height: 240rpx;" mode="aspectFit" :src="items.main_img"></image>
					</view>
					<view class="goods-detail">
						<view class="goods-name">{{ items.name }}</view>
						<view class="goods-mess">
							<view class="goods-tips">{{ items.goods_date === date?'今日推荐': dateMode(new Date(items.goods_date), 'weeks')}}
							</view>
							<view class="goods-minutiae">
								{{ items.description }}
							</view>
						</view>
						<view class="goods-sale">
							<view class="goods-price">￥ {{ items.goods_date === date?items.buy_price:items.front_price }}</view>
							<view class="goods-number" @click.stop v-if="items.stock > 0">
								<view class="reduce-button" v-if="cartNumber(items.goods_date)>0">
									<image style="width: 100%; height: 100%;" mode="aspectFit" :src="icons.reduce" @click.stop="changeCart('reduce', items)"></image>
								</view>
								<view class="number-input" v-if="cartNumber(items.goods_date)>0">{{ cartNumber(items.goods_date) }}</view>
								<view class="add-button">
									<image style="width: 100%; height: 100%;" mode="aspectFit" :src="items.goods_date === date && realATime < (new Date()).getTime()?icons.add_2:icons.add"
									 @click.stop="changeCart('add', items)"></image>
								</view>
							</view>
							<view v-else class="goods-number">
								已售罄
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<shop-cart :toPage="toPage"></shop-cart>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import shopCart from "@/components/shop-cart/index.vue"
	export default {
		components: {
			shopCart
		},
		data() {
			return {
				date: "",
				list: [],
				info: [{
					content: '/static/images/banner@3x.png'
				}, {
					content: '/static/images/banner@3x.png'
				}, {
					content: '/static/images/banner@3x.png'
				}],
				current_index: 0,
				icons: {
					locate: '/static/images/icons/icon_dw@3x.png',
					reduce: '/static/images/icons/reduce@3x.png',
					add: '/static/images/icons/icon_tj@3x.png',
					add_2: '/static/images/icons/add_2@3x.png',
					clear: '/static/images/icons/icon_qk@3x.png',
					today: '/static/images/icons/icon_wc@3x.png',
					tomorrow: '/static/images/icons/icon_yd@3x.png',
				},
				toPage: '/pages/order/verify',
				realATime: undefined
			}
		},
		computed: {
			...mapGetters([
				'goodsCart', 'currentEqiupment'
			])
		},
		watch: {
			'currentEqiupment.eqiupment_id': {
				handler: function(val, oldval) {
					this.getList()
				},
				deep: true //对象内部的属性监听，也叫深度监听
			}
		},
		created() {
			let key = this.getUrlKey('key')
			if (key) {
				this.getMess(key);
			} else {
				const _this = this;
				let token = "";
				uni.getStorage({
					key: 'uerInfo',
					success: function(res) {
						_this.keepLogin(res.data.token)
					}
				});
			}

			const nowTimeDate = new Date();
			nowTimeDate.setHours(12, 30, 0, 0); //设为当天0点0分0秒0毫秒。
			this.realATime = nowTimeDate.getTime();

			this.date = this.dateMode(new Date(), 'nowDate')
			this.getAddress()
			// 判断购物车内是否有过期餐品有则移除
			const list = this.goodsCart
			for (let i = 0; i < list.length; i++) {
				if (new Date(list[i].date) < new Date(this.date)) {
					let shopData = {
						index: i,
						type: 4 // 判断是哪种类型的操作 1.新增商品，2.新增数量，3.减少数量，4.减少商品
					}
					// 在vuex里面做赋值
					this.$store.commit('addToCart', shopData);
				}
			}
		},
		methods: {
			keepLogin(token) {
				const path = {
					app: "wx",
					api: "api_wx_user_keepLogin",
					version: "1.0",
					type: "1",
					data: {
						token: token
					}
				}
				this.sendSock(path)
			},
			getMess(key) {
				const path = {
					app: "wx",
					api: "api_wx_user_login",
					version: "1.0",
					type: "1",
					data: {
						key: key
					}
				}
				this.sendSock(path)
			},
			getAddress() {
				this.getEquipment(24.49579468999999, 118.19040549999994);
				// console.log('获取定位')
				// const _this = this
				// window.AMap.plugin('AMap.Geolocation', function() {
				// 	var geolocation = new window.AMap.Geolocation({
				// 		enableHighAccuracy: true, // 是否使用高精度定位，默认:true
				// 		timeout: 10000, // 超过10秒后停止定位，默认：无穷大
				// 		buttonOffset: new window.AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
				// 		zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
				// 		buttonPosition: 'RB'
				// 	});
				// 	geolocation.getCurrentPosition(async (status, result) => {
				// 		console.log('result', result)
				// 		if (status === 'complete') {
				// 			console.log('result.position.lat, result.position.lng', result.position.lat, result.position.lng)
				// 			_this.getEquipment(result.position.lat, result.position.lng);
				// 		} else {
				// 			console.log('定位失败')
				// 			reject(new Error('定位失败'));
				// 			Vue.prototype.$toast('定位失败');
				// 		}
				// 	});
				// });
			},
			getEquipment(latitude, longitude) {
				const path = {
					app: "wx",
					api: "api_wx_index_getEquipmentList",
					version: "1.0",
					type: "1,2",
					data: {
						longitude: latitude,
						latitude: longitude
					}
				}
				this.sendSock(path)
			},
			getList() {
				const path = {
					app: "wx",
					api: "api_wx_index_getList",
					version: "1.0",
					type: "1",
					data: {
						equipment_id: this.currentEqiupment.eqiupment_id
					}
				}
				this.sendSock(path)
			},
			change(e) {
				this.current_index = e.detail.current;
			},
			changeCart(name, items) {
				const goodList = this.goodsCart;
				var goodDate = goodList.map(officer => officer.date);
				const index = goodDate.indexOf(items.goods_date)
				if (name === "reduce") {
					const number = this.goodsCart[index].number;
					let shopData = {
						index: index,
						type: 4 // 判断是哪种类型的操作 1.新增商品，2.新增数量，3.减少数量，4.减少商品
					}

					if (number > 1) {
						shopData.type = 3
					}

					// 在vuex里面做赋值
					this.$store.commit('addToCart', shopData);
				} else if (name === "add") {

					// 判断是否是今日订单 今日定单超过12点30分不能点
					if (items.goods_date === this.dateMode(new Date(), 'nowDate') && this.realATime < (new Date()).getTime()) {
						return false
					}

					if (index === -1 && items.stock >= 1) {
						let price = 0;
						if (this.date === items.goods_date) {
							price = items.buy_price;
						} else {
							price = items.front_price
						}

						const goodList = {
							goods_id: items.id,
							goods_name: items.name,
							main_img: items.main_img,
							price: price,
							number: 1,
							date: items.goods_date,
							stock: items.stock
						}
						const shopData = {
							goodList: goodList,
							type: 1 // 判断是哪种类型的操作 1.新增商品，2.新增数量，3.减少数量
						}
						// 在vuex里面做赋值
						this.$store.commit('addToCart', shopData);
					} else {
						const number = this.goodsCart[index].number
						if (number < items.stock) {
							const shopData = {
								index: index,
								type: 2 // 判断是哪种类型的操作 1.新增商品，2.新增数量，3.减少数量
							}
							this.$store.commit('addToCart', shopData);
						} else {
							uni.showToast({
								icon: "none",
								title: '库存不足',
								duration: 2000
							});
						}
					}
				}
			},
			cartNumber(date) {
				const data = this.goodsCart;
				let number = 0
				if (data.length > 0) {
					data.forEach(element => {
						if (date === element.date) {
							number = element.number;
						}
					})
				}
				return number
			},
			showDtail(id, date) {
				const _this = this;
				uni.navigateTo({
					url: '/pages/meal-picker/detail?id=' + id + '&date=' + date + '&' + _this.version
				})
			},
			open() {
				const _this = this;
				uni.navigateTo({
					url: '/pages/meal-picker/list' + '?' + _this.version
				})
			},
			sendSock(path) {
				if (this.$store.state.socketOpen) {
					uni.sendSocketMessage({
						data: JSON.stringify(path)
					});
				} else {
					this.$store.state.socketMsgQueue.push(JSON.stringify(path));
				}
				const _this = this
				uni.onSocketMessage(function(res) {
					_this.getSock(res.data)
				});
			},
			getSock(res) {
				if (res !== '{"type":"ping"}') {
					const resj = JSON.parse(res);
					if (resj.code === -1) {
						uni.showToast({
							icon: "none",
							title: resj.message,
							duration: 2000
						});
					} else if (resj.code === 403) {
						const key = this.getUrlKey('key')
						this.getMess(key);
					} else {
						if (resj.api === "api_wx_user_login") {
							this.$store.commit('login', resj.data);
							this.temporary()
						} else if (resj.api === "api_wx_user_keepLogin") {
							this.$store.commit('login', resj.data);
							this.temporary()
						} else if (resj.api === "api_wx_index_getList") {
							this.list = resj.data
						} else if (resj.api === "api_wx_index_getEquipmentList") {

							if (resj.data.length > 0) {

								// vuex保存设备数据
								this.$store.commit('currentEq', resj.data[0]);
								this.getList()
							}
						}
					}
				}
			}
		}
	}
</script>
<style>
	.content {
		padding: 0 30rpx 120rpx 30rpx;
	}

	.locate-images {
		width: 30rpx;
		height: 30rpx;
		display: flex;
		align-items: center;
	}

	.triangle_border_right {
		border-width: 8rpx 8rpx 0rpx 0rpx;
		border-style: solid;
		border-color: transparent #333 transparent transparent;
		/*透明 透明 透明 灰*/
		position: absolute;
		bottom: 8rpx;
		margin-left: 10rpx;
	}

	.locate-item {
		display: flex;
		align-items: center;
		position: relative;
		margin: 40rpx 0;
	}

	.locate-title {
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: bold;
		margin-left: 9rpx;
	}

	.goods-title,
	.goods-icon,
	.goods-content {
		display: flex;
		align-items: center;
	}

	.goods-mess {
		display: flex;
		align-items: flex-start;
		margin-top: 20rpx;
		height: 90rpx;
	}

	.goods-icon {
		width: 36rpx;
		height: 36rpx;
	}

	.items-title {
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #222222;
		margin: 0 17rpx;
		line-height: 1;
	}

	.goods-note {
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #999999;
	}

	.goods-img {
		width: 240rpx;
		height: 240rpx;
	}

	.goods-content {
		background: rgba(255, 255, 255, 1);
		box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin: 40rpx 0 60rpx 0;
	}

	.goods-detail {
		padding: 30rpx 30rpx;
		box-sizing: border-box;
		flex: 1;
	}

	.goods-name {
		font-size: 32rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #222222;
		line-height: 1;
	}

	.goods-tips {
		width: 104rpx;
		height: 30rpx;
		background: url('~@/static/images/tips2@3x.png') no-repeat;
		background-size: 100% 100%;
		font-size: 20rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
		word-wrap: break-word;
		white-space: nowrap;
	}

	.goods-minutiae {
		flex: 1;
		margin-left: 10rpx;
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 500;
		color: #666666;
		line-height: 1;
	}

	.goods-sale {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.goods-price {
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: #FF5500;
	}

	.goods-number {
		display: flex;
		align-items: center;
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: rgba(51, 51, 51, 1);
		line-height: 1;
	}

	.reduce-button,
	.add-button {
		width: 48rpx;
		height: 48rpx;
	}

	.number-input {
		text-align: center;
		width: 60rpx;
		font-size: 36rpx;
		font-family: PingFang SC;
		font-weight: bold;
		color: rgba(51, 51, 51, 1);
		line-height: 1;
	}
</style>
